﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace LogAnalysis {
	public partial class FolderLogs : Form {
		private string tablename = string.Empty;
		private string[] fields = new string[] { };
		public FolderLogs() {
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e) {
			folderBrowserDialog1.SelectedPath = tbFolder.Text;
			if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
				tbFolder.Text = folderBrowserDialog1.SelectedPath;
			}

		}

		private void button2_Click(object sender, EventArgs e) {

			backgroundWorker1.RunWorkerAsync(tbFolder.Text);
			buttonCancel.Enabled = true;
			buttonInit.Enabled = buttonStart.Enabled = false;
		}

		private void button3_Click(object sender, EventArgs e) {
			ResetData(tbFolder.Text);
			MessageBox.Show("完成");
			return;
		}

		private void GetTableAndFields(string folder) {
			string[] files = Directory.GetFiles(folder);
			if (files.Length > 0) {
				tablename = Path.GetFileNameWithoutExtension(files[0]);
				StreamReader reader = new StreamReader(files[0]);
				string line = string.Empty;
				while (!line.StartsWith("#Fields:") && !reader.EndOfStream) {
					line = reader.ReadLine();
				}
				reader.Close();
				reader.Dispose();
				line = line.Remove(0, 8);
				fields = line.Trim().Split(' ');
			}
		}

		private void ResetData(string folder) {
			GetTableAndFields(folder);

			if (fields.Length > 0) {
				string create = "drop table " + tablename;
				try {
					Utility.ExecuteScript(create);
				}
				catch (Exception) {
				}
				StringBuilder script = new StringBuilder();
				script.AppendFormat("CREATE TABLE [{0}](", tablename);

				for (int i = 0; i < fields.Length; i++) {
					string temp = string.Format("[{0}] [nvarchar]", fields[i]);
					if (fields[i].IndexOf("uri") > -1
						|| fields[i].IndexOf("User-Agent") > -1
						|| fields[i].IndexOf("Referer") > -1) {
						temp += "(4000) NULL";
					}
					else {
						temp += "(255) NULL";
					}
					if (i > 0) {
						temp = "," + temp;
					}
					script.Append(temp);
				}
				script.Append(")");
				Utility.ExecuteScript(script.ToString());

			}
		}

		private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
			var bgworker = sender as BackgroundWorker;
			//bgworker.ReportProgress(0, new KeyValuePair<string, string>("Overall", "初始化数据...."));
			//ResetData();
			//bgworker.ReportProgress(0, new KeyValuePair<string, string>("Overall", "初始化数据完成"));
			GetTableAndFields((string)e.Argument);
			string[] files = Directory.GetFiles((string)e.Argument);
			for (int i = 0; i < files.Length; i++) {
				long fileSize = new FileInfo(files[i]).Length;
				StreamReader reader = new StreamReader(files[i], true);
				long counter = 0;
				int currentSize = 0;
				while (!reader.EndOfStream) {
					string line = reader.ReadLine();
					currentSize += Encoding.Default.GetByteCount(line);
					if (bgworker.CancellationPending) {
						e.Cancel = true;
						return;
					}
					if (!line.StartsWith("#")) {
						KeyValuePair<string, object>[] sqlparams = new KeyValuePair<string, object>[fields.Length];
						string[] values = line.Split(' ');
						string script = string.Format("INSERT INTO [{0}](", tablename) + "[" + string.Join("],[", fields) + "])VALUES (";
						for (int k = 0; k < fields.Length; k++) {
							string sqlparamName = "@sqlparam" + k;
							sqlparams[k] = new KeyValuePair<string, object>(sqlparamName, values[k]);
							script += sqlparamName + ",";
						}
						script = script.TrimEnd(',');
						script += ")";
						Utility.ExecuteScript(script, sqlparams);
					}
					counter++;
					int progress = (int)(((double)currentSize / (double)fileSize) * 100);
					bgworker.ReportProgress(progress, new KeyValuePair<string, string>("Current", files[i] + ":" + counter.ToString()));
					Debug.WriteLine(progress);
				}
				reader.Close();
				reader.Dispose();
				bgworker.ReportProgress((int)((((double)i + 1) / (double)files.Length) * 100), new KeyValuePair<string, string>("Overall", string.Format("{0} / {1}", i + 1, files.Length)));
			}
		}

		private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
			var state = (KeyValuePair<string, string>)e.UserState;
			if (state.Key == "Overall") {
				pbOverall.Value = e.ProgressPercentage;
				labelOverall.Text = string.Format("总体进度:{1}% - {0}", state.Value, e.ProgressPercentage);
			}
			if (state.Key == "Current") {
				pbCurrent.Value = e.ProgressPercentage;
				labelCurrent.Text = string.Format("当前进度:{1}% - {0}", state.Value, e.ProgressPercentage);
			}
		}

		private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
			if (e.Cancelled) {
				MessageBox.Show("已取消");
			}
			else if (e.Error != null) {
				MessageBox.Show("发生错误退出");
			}
			else {
				MessageBox.Show("完成");
			}
			buttonCancel.Enabled = false;
			buttonInit.Enabled = buttonStart.Enabled = true;

		}

		private void buttonCancel_Click(object sender, EventArgs e) {
			backgroundWorker1.CancelAsync();
		}
	}
}
